package concurrent;

/**
 * jdk内置锁不能被中断
 * synchronized只有获取到锁的线程才能中断，等待锁时不会中断，一直等到线程获取锁，才触发InterruptedException
 *
 * 以下是运行结果
 * t1 enter
 * start lock t1
 * t2 enter
 * t2 interrupt...        // 此处等待了好久好久，直到t2获取到锁才报中断错误
 * java.lang.InterruptedException: sleep interrupted
 * end lock t1
 * 	at java.lang.Thread.sleep(Native Method)
 * start lock t2
 * 	at concurrent.Uninterruptible.lambda$main$1(Uninterruptible.java:45)
 * t2 interruptedException
 * 	at concurrent.Uninterruptible$$Lambda$2/1134517053.run(Unknown Source)
 * 	at java.lang.Thread.run(Thread.java:745)
 *
 * Process finished with exit code 0
 */
public class Uninterruptible {
    private static final Object o1 = new Object();

    public static void main(String[] args) throws InterruptedException {

        Thread thread1 = new Thread(() -> {
            System.out.println("t1 enter");
            synchronized (o1) {
                try {
                    System.out.println("start lock t1");
                    Thread.sleep(20000);
                    System.out.println("end lock t1");
                } catch (InterruptedException e) {
                    System.out.println("t1 interruptedException");
                    e.printStackTrace();
                }
            }
        });


        Thread thread2 = new Thread(() -> {
            System.out.println("t2 enter");
            synchronized (o1) {
                try {
                    System.out.println("start lock t2");
                    Thread.sleep(1000);
                    System.out.println("end lock t2");
                } catch (InterruptedException e) {
                    System.out.println("t2 interruptedException");
                    e.printStackTrace();
                }
            }
        });

        thread1.start();
        thread2.start();

        // 让两个线程充分启动，再执行t2中断
        Thread.sleep(1000);

        thread2.interrupt();
        System.out.println("t2 interrupt...");

    }

}